<template>
  <div class="student-portal">
    <div v-if="isUserIdInvalid">
      <el-alert
        title="正在加载用户信息..."
        type="info"
        show-icon
        :closable="false"
      />
      <el-progress :percentage="loadingProgress" :indeterminate="true" />
    </div>
    
    <!-- 导航选项卡 -->
    <el-tabs v-else v-model="activeTab" class="portal-tabs" @tab-change="handleTabChange">
      <!-- 1. 浏览社团招新信息 -->
      <el-tab-pane label="浏览社团" name="browse">
        <ClubBrowse 
          ref="clubBrowseRef" 
          :current-user-id="currentUserId"
          @switch-to-applications="activeTab = 'applications'"
        />
      </el-tab-pane>

      <!-- 2. 我的申请 -->
      <el-tab-pane label="我的申请" name="applications">
        <MyApplications 
          ref="myApplicationsRef" 
          :current-user-id="currentUserId"
          @switch-to-browse="activeTab = 'browse'"
          @switch-to-interviews="activeTab = 'interviews'"
        />
      </el-tab-pane>

      <!-- 3. 面试预约 -->
      <el-tab-pane label="面试预约" name="interviews">
        <InterviewManagement 
          ref="interviewManagementRef" 
          :current-user-id="currentUserId"
        />
      </el-tab-pane>

      <!-- 4. 智能匹配推荐 -->
      <el-tab-pane label="智能推荐" name="recommendations">
        <SmartRecommendations 
          ref="smartRecommendationsRef" 
          :current-user-id="currentUserId"
          @switch-to-browse="activeTab = 'browse'"
          @apply-from-recommendation="handleApplyFromRecommendation"
        />
      </el-tab-pane>

      <!-- 5. 个人资料 -->
      <el-tab-pane label="个人资料" name="profile">
        <StudentProfile 
          ref="studentProfileRef" 
          :current-user-id="currentUserId"
        />
      </el-tab-pane>
      
      <!-- 6. 调试信息 -->
      <el-tab-pane label="调试信息" name="debug">
        <div v-if="currentUserId">
          <h3>用户ID调试信息</h3>
          <p>当前用户ID: {{ currentUserId }}</p>
          <p>用户ID类型: {{ typeof currentUserId }}</p>
          <p>是否有效: {{ !isUserIdInvalid }}</p>
        </div>
        <div v-else>
          <p>未获取到用户ID信息</p>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import ClubBrowse from './ClubBrowse.vue'
import MyApplications from './MyApplications.vue'
import InterviewManagement from './InterviewManagement.vue'
import SmartRecommendations from './SmartRecommendations.vue'
import StudentProfile from './StudentProfile.vue'
import useUserStore from '@/store/modules/user'

// Get current user from store
const userStore = useUserStore()

// 获取当前用户ID（从store中获取）
const currentUserId = ref('')
const loadingProgress = ref(0)

// 计算属性：检查用户ID是否无效
const isUserIdInvalid = computed(() => {
  const userId = currentUserId.value
  // 检查是否为空、未定义、null或空字符串
  return !userId || 
         userId === 'undefined' || 
         userId === 'null' || 
         userId === '' || 
         (typeof userId === 'string' && userId.trim() === '')
})

// 定义主要状态变量
const activeTab = ref('browse')

// 组件引用
const clubBrowseRef = ref()
const myApplicationsRef = ref()
const interviewManagementRef = ref()
const smartRecommendationsRef = ref()
const studentProfileRef = ref()

// 标签切换处理
const handleTabChange = (tabName) => {
  console.log('切换到标签:', tabName)
  // 各组件会在自己内部处理数据加载
}

// 从推荐组件申请的处理函数
const handleApplyFromRecommendation = (recommendation) => {
  // 切换到浏览标签并触发申请
  activeTab.value = 'browse'
  // 可以通过组件引用调用相关方法
  if (clubBrowseRef.value) {
    clubBrowseRef.value.handleApplyFromRecommendation?.(recommendation)
  }
}

// 更新用户ID的方法
const updateCurrentUserId = () => {
  const userId = userStore.id || ''
  console.log('尝试更新用户ID，当前store中的ID:', userStore.id, '当前组件中的ID:', currentUserId.value, '新ID:', userId)
  if (userId && userId !== currentUserId.value && userId !== 'undefined' && userId !== 'null' && userId !== '') {
    currentUserId.value = String(userId) // 确保转换为字符串
    console.log('用户ID已更新:', userId)
  } else if (!userId || userId === 'undefined' || userId === 'null' || userId === '') {
    console.log('用户ID为空或无效，可能用户未登录或store未初始化')
  } else {
    console.log('用户ID未变化，当前值:', userId)
  }
}

// 页面初始化
onMounted(() => {
  console.log('学生门户组件已挂载，当前store中的用户ID:', userStore.id)
  console.log('userStore对象:', userStore)
  // 确保用户ID已设置
  updateCurrentUserId()
  
  // 添加一个定时器确保用户ID正确设置
  const interval = setInterval(() => {
    console.log('轮询检查用户ID...')
    loadingProgress.value = (loadingProgress.value + 10) % 100
    updateCurrentUserId()
    if (!isUserIdInvalid.value) {
      console.log('用户ID已成功设置，停止轮询')
      clearInterval(interval)
    }
  }, 200)
  
  // 设置超时时间，避免无限循环
  setTimeout(() => {
    console.log('轮询超时，停止更新用户ID')
    clearInterval(interval)
    
    // 如果超时后仍然没有用户ID，尝试从localStorage获取
    if (isUserIdInvalid.value) {
      const storedUserId = localStorage.getItem('userId')
      if (storedUserId && storedUserId !== 'undefined' && storedUserId !== 'null') {
        currentUserId.value = storedUserId
        console.log('从localStorage获取用户ID:', storedUserId)
      } else {
        console.log('localStorage中也没有有效的用户ID')
      }
    }
  }, 5000)
})

// 监听用户存储变化
watch(() => userStore.id, (newId) => {
  console.log('监听到用户store ID变化:', newId)
  if (newId && newId !== 'undefined' && newId !== 'null' && newId !== '') {
    currentUserId.value = String(newId) // 确保转换为字符串
    console.log('用户ID更新:', newId)
    // 同时保存到localStorage
    localStorage.setItem('userId', String(newId))
  }
})

// 监听currentUserId变化并强制更新子组件
watch(currentUserId, (newId) => {
  console.log('监听到currentUserId变化:', newId)
  if (newId && newId !== 'undefined' && newId !== 'null' && newId !== '') {
    console.log('当前用户ID更新为:', newId)
    // 强制刷新所有子组件
    if (clubBrowseRef.value && typeof clubBrowseRef.value.loadClubs === 'function') {
      clubBrowseRef.value.loadClubs()
    }
    if (myApplicationsRef.value && typeof myApplicationsRef.value.loadApplications === 'function') {
      myApplicationsRef.value.loadApplications()
    }
    if (interviewManagementRef.value && typeof interviewManagementRef.value.loadInterviews === 'function') {
      interviewManagementRef.value.loadInterviews()
    }
    if (smartRecommendationsRef.value && typeof smartRecommendationsRef.value.loadRecommendations === 'function') {
      smartRecommendationsRef.value.loadRecommendations()
    }
    if (studentProfileRef.value && typeof studentProfileRef.value.loadProfile === 'function') {
      studentProfileRef.value.loadProfile()
    }
  }
})
</script>

<style scoped>
.student-portal {
  min-height: 100vh;
  background: #f5f7fa;
}

.portal-tabs {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.portal-tabs .el-tabs__content {
  padding: 0;
}
</style>